package com.qxf.service.jfreechart;

import java.awt.Color;
import java.awt.Font;
import java.awt.RenderingHints;
import java.io.IOException;
import java.text.NumberFormat;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PieLabelLinkStyle;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.title.LegendTitle;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.ui.TextAnchor;
import org.jfree.util.SortOrder;

public class ChartHelper {

	private StatisticData chartInfo;
	private List<StatisticData> dataList;
	private HttpServletRequest request;
	private HttpSession session;
	
	@SuppressWarnings("unused")
	private ChartHelper() {
		
	}
	
	public ChartHelper(StatisticData chartInfo, List<StatisticData> dataList, HttpServletRequest request) {
		this.chartInfo = chartInfo;
		this.dataList = dataList;
		this.request = request;
		this.session = request.getSession();
		StandardChartTheme theme = new StandardChartTheme("CN") {
			private static final long serialVersionUID = 4135414099289159728L;
			public void apply(JFreeChart chart) {
		        chart.getRenderingHints().put(RenderingHints.KEY_TEXT_ANTIALIASING,   
		                RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
		        super.apply(chart);
		    }
		}; 
		theme.setExtraLargeFont(new Font("宋体", Font.PLAIN, 20)); 
		theme.setLargeFont(new Font("宋体", Font.PLAIN, 14)); 
		theme.setRegularFont(new Font("宋体", Font.PLAIN, 12)); 
		theme.setSmallFont(new Font("宋体", Font.PLAIN, 10)); 
		ChartFactory.setChartTheme(theme);
	}
	
	public String getPieChart() throws IOException {
		JFreeChart chart =  ChartFactory.createPieChart(
				chartInfo.getChartName(),
				getPieDataset(), true, true, true);
		setChartStyle(chart);
		String filename = ChartUtil.getChartPicPath(chart, this.session);
		return request.getContextPath() + "/displaychart?filename=" + filename;
	}
	
	public String getBarChart() throws IOException {
		JFreeChart chart = ChartFactory.createBarChart(
				chartInfo.getChartName(),
				((BarStatisticData)chartInfo).getCategoryAxisLabel(),
				((BarStatisticData)chartInfo).getValueAxisLabel(),
				getBarDataset(),
				PlotOrientation.HORIZONTAL, true, true, true);
		setChartStyle(chart);
		String filename = ChartUtil.getChartPicPath(chart, this.session);
		return request.getContextPath() + "/displaychart?filename=" + filename;
	}
	
	private DefaultPieDataset getPieDataset() {
		PieStatisticData data = null;
		DefaultPieDataset dataset = new DefaultPieDataset();
		Iterator<StatisticData> list = this.dataList.listIterator();
		while(list.hasNext()) {
			data = (PieStatisticData)list.next();
			dataset.setValue(data, data.getCount());
		}
		dataset.sortByValues(SortOrder.ASCENDING);
		return dataset;
	}
	
	private DefaultCategoryDataset getBarDataset() {
		BarStatisticData data = null;
		DefaultCategoryDataset dataset = new DefaultCategoryDataset();
		Iterator<StatisticData> list = this.dataList.listIterator();
		while(list.hasNext()) {
			data = (BarStatisticData)list.next();
			dataset.setValue(data.getCount(), data.getName(), data.getCategory());
		}
		return dataset;
	}
	
	private JFreeChart setChartStyle(JFreeChart chart) {
		// 数据区
		Plot plot = chart.getPlot();
		// 是否显示边框线
		plot.setOutlineVisible(false);
		// 设置背景色
		plot.setBackgroundPaint(Color.decode("#E1EEF5"));
		// 背景透明度
		plot.setBackgroundAlpha(1f);
		// 前景透明度
		plot.setForegroundAlpha(1f);
		// 设置无数据是显示信息
		plot.setNoDataMessage("没有数据！");
		if(plot instanceof PiePlot) {
			// 标签背景色
			((PiePlot) plot).setLabelBackgroundPaint(Color.WHITE);
			// 忽略空数据
			((PiePlot) plot).setIgnoreNullValues(false);
			// 设置标签线型
			((PiePlot) plot).setLabelLinkStyle(PieLabelLinkStyle.STANDARD);
			((PiePlot) plot).setLabelLinkMargin(0.1);
			// 标签内容格式
			((PiePlot) plot).setLabelGenerator(new StandardPieSectionLabelGenerator("{0}:{2}"));
		}
		if(plot instanceof CategoryPlot) {
			((CategoryPlot) plot).setColumnRenderingOrder(SortOrder.DESCENDING);
			((CategoryPlot) plot).setRangeGridlinesVisible(true);
//			((CategoryPlot) plot).getDomainAxis().setLowerMargin(0.1);
//			((CategoryPlot) plot).getDomainAxis().setUpperMargin(0.1);
			BarRenderer renderer = new BarRenderer();
			renderer.setMaximumBarWidth(5);
			renderer.setItemMargin(-1);
			renderer.setMinimumBarLength(0.2);
			renderer.setBaseItemLabelsVisible(true);
			renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER));
			renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator("{2}", NumberFormat.getNumberInstance()));
			((CategoryPlot) plot).setRenderer(renderer);
		}
		
		// 分类区
		LegendTitle legend = chart.getLegend();
		legend.setBackgroundPaint(Color.WHITE);
		
		return chart;
	}

}
